#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2024/9/20 18:03
# @Author  : Tom_zc
# @FileName: majun_helper.py
# @Software: PyCharm
import time
import logging

from .request_handler import RequestHandler

logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s  %(levelname)s:%(message)s")


class MaJunHelper:
    token_url = "{}/api/ci-backend/ci-portal/webhook/codecheck/v1/token"
    check_ci_url = "{}/api/ci-backend/ci-portal/webhook/codecheck/v1/task"
    check_ci_status_url = "{}/api/ci-backend/ci-portal/webhook/codecheck/v1/task/status"
    add_repo_url = "{}/api/ci-backend/ci-portal/webhook/codecheck/v1/ubmc/add/repo"

    repo_exist_failed_code = "the repo already existed"

    def __init__(self, app_token, domain, request_handler=RequestHandler()):
        self.domain = domain
        self.request_handler = request_handler
        self.app_token = app_token
        self.token = None
        self.refresh_token()

    def refresh_token(self):
        body = {"static_token": self.app_token}
        _, resp = self.request_handler.post(self.token_url.format(self.domain), json_data=body)
        if not str(resp.get("code")).startswith("20"):
            raise Exception("get token failed, and return is:{}".format(resp))
        self.token = resp["data"]

    def create_task(self, pr_url):
        body = {
            "pr_url": pr_url,
            "token": self.token,
            "projectName": "openUBMC"
        }
        _, resp = self.request_handler.post(self.check_ci_url.format(self.domain), json_data=body)
        return resp["task_id"], resp["uuid"]

    def check_task(self, task_id, uuid):
        count = 0
        while True:
            body = {
                "task_id": task_id,
                "uuid": uuid,
                "token": self.token
            }
            _, resp = self.request_handler.post(self.check_ci_status_url.format(self.domain), json_data=body)
            detail_code = int(resp["code"])
            if detail_code == 200:
                return resp["state"].upper(), resp["data"]
            elif detail_code == 500:
                return "Failed", resp["msg"]
            elif detail_code == 401:
                self.refresh_token()
            elif detail_code == 100:
                logging.info("waiting for return codeCheck result for majun platform and count:{}.....".format(count))
                time.sleep(10)
                count += 1
            if count > 10 * 60 / 5:
                return "Timeout", resp["msg"]

    def add_repo(self, gitcode_domain, org, repo_name, private):
        data = {
            "domainName": "openUBMC",
            "projectName": "openUBMC",
            "repoName": repo_name,
            "repoUrl": "{}/{}/{}.git".format(gitcode_domain, org, repo_name),
            "visibility": "private" if private.lower() == "privacy" else "public",
            "repoLanguage": "LUA",
            "token": self.token,
            "branchName": "main"
        }
        _, resp = self.request_handler.post(self.add_repo_url.format(self.domain), json_data=data)
        if resp["code"].startswith("20"):
            return resp
        if not resp["code"].startswith("20") and resp["msg"] == self.repo_exist_failed_code:
            return resp
        raise Exception("add repo failed, and reason is:{}".format(str(resp)))
